<!--
 * 主对话容器组件
 * 功能：包含功能选择按钮、对话历史和输入区域的完整对话界面
 * 作者：MetasoCreator Team
 * 创建时间：2025-01-19
 * 修改时间：2025-01-19
-->

<template>
  <div class="chat-container">
    <!-- 功能选择按钮组 -->
    <div class="function-buttons-section">
      <FunctionButtons
        v-model:activeMode="currentMode"
        @mode-change="handleModeChange"
      />
    </div>

    <!-- 聊天历史区域 -->
    <div class="chat-history-section">
      <ChatHistory 
        :messages="props.messages"
        :loading="props.loading"
        class="scrollbar-thin"
      />
    </div>
    
    <!-- 输入区域 -->
    <div class="input-section">
      <InputArea 
        v-model:message="inputMessage"
        @send-message="handleSendMessage"
        @search="handleSearch"
        :loading="props.loading"
        :mode="currentMode"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import FunctionButtons from './FunctionButtons.vue'
import ChatHistory from './ChatHistory.vue'
import InputArea from './InputArea.vue'
import { searchAPI, qaAPI } from '../../api/index.js'

// 定义props
const props = defineProps({
  messages: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['send-message', 'search'])

// 处理发送消息
const handleSendMessage = (message) => {
  emit('send-message', message)
}

// 处理搜索
const handleSearch = (query, scope) => {
  emit('search', query, scope)
}

// 响应式数据
const currentMode = ref('web_search') // 当前模式：web_search, academic_search, qa, content_creation
const inputMessage = ref('')
const isLoading = ref(false)
const messages = reactive([])

// 计算属性
const currentModeLabel = computed(() => {
  const labels = {
    web_search: '网页搜索',
    academic_search: '学术搜索',
    qa: '智能问答',
    content_creation: '内容创作'
  }
  return labels[currentMode.value] || '未知模式'
})

// 方法
const handleModeChange = (mode) => {
  currentMode.value = mode
  ElMessage.info(`已切换到${currentModeLabel.value}模式`)
}

const handleSend = async (message) => {
  if (!message.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  // 清空输入框
  inputMessage.value = ''

  try {
    let response
    
    // 根据当前模式调用不同的API
    switch (currentMode.value) {
      case 'web_search':
        // 触发搜索事件，由父组件处理
        emit('search', message, 'webpage')
        return
      case 'academic_search':
        // 触发搜索事件，由父组件处理
        emit('search', message, 'scholar')
        return
      case 'qa':
      case 'content_creation':
        // 触发问答事件，由父组件处理
        emit('send-message', message)
        return
      default:
        throw new Error('未知的模式')
    }

  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请检查网络连接')
  }
}

const handleRegenerate = async (messageId) => {
  const messageIndex = messages.findIndex(msg => msg.id === messageId)
  if (messageIndex === -1) return

  const message = messages[messageIndex]
  if (message.type !== 'ai') return

  // 找到对应的用户消息
  const userMessage = messages[messageIndex - 1]
  if (!userMessage || userMessage.type !== 'user') return

  // 删除原AI消息
  messages.splice(messageIndex, 1)
  
  // 重新发送
  await handleSend(userMessage.content)
}

const handleCopy = (content) => {
  navigator.clipboard.writeText(content).then(() => {
    ElMessage.success('内容已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

const handleDelete = async (messageId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条消息吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = messages.findIndex(msg => msg.id === messageId)
    if (index !== -1) {
      messages.splice(index, 1)
      ElMessage.success('消息已删除')
    }
  } catch {
    // 用户取消删除
  }
}

const handleAttach = () => {
  ElMessage.info('附件功能开发中...')
}

const handleVoice = () => {
  ElMessage.info('语音功能开发中...')
}

// 初始化欢迎消息
const initWelcomeMessage = () => {
  const welcomeMessage = {
    id: 0,
    type: 'ai',
    content: `欢迎使用 MetasoCreator！🎉

我是您的智能助手，可以帮您：

🔍 **网页搜索** - 搜索最新的网络信息
📚 **学术搜索** - 查找学术论文和研究资料  
💡 **智能问答** - 回答各种问题并提供详细解释
✍️ **内容创作** - 协助您创作各类文本内容

请选择上方的功能模式，然后在下方输入您的问题或需求。让我们开始吧！`,
    timestamp: new Date(),
    mode: 'system',
    welcome: true
  }
  messages.push(welcomeMessage)
}

// 生命周期
onMounted(() => {
  initWelcomeMessage()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--bg-primary);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.function-buttons-section {
  flex-shrink: 0;
  padding: 20px 20px 0 20px;
}

.chat-history-section {
  flex: 1;
  min-height: 0;
  padding: 20px;
  overflow: hidden;
}

.input-section {
  flex-shrink: 0;
  padding: 0 20px 20px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .function-buttons-section,
  .chat-history-section,
  .input-section {
    padding-left: 15px;
    padding-right: 15px;
  }
  
  .function-buttons-section {
    padding-top: 15px;
  }
  
  .input-section {
    padding-bottom: 15px;
  }
}

@media (max-width: 480px) {
  .function-buttons-section,
  .chat-history-section,
  .input-section {
    padding-left: 10px;
    padding-right: 10px;
  }
  
  .function-buttons-section {
    padding-top: 10px;
  }
  
  .input-section {
    padding-bottom: 10px;
  }
}

/* 暗色主题适配 */
:root[data-theme="dark"] .chat-container {
  background: var(--bg-primary);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
</style>